#pragma once

#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <queue>
#include<semaphore.h>

const static int defaultnum = 10;

template<class T>
class Ringqueue
{
    // 申请信号量 --
    void P(sem_t& sem)
    {
        sem_wait(&sem);
    }
    // 退还信号量 ++
    void V(sem_t& sem)
    {
        sem_post(&sem);
    }
    void Lock(pthread_mutex_t& mutex)
    {
        pthread_mutex_lock(&mutex);
    }
    void UnLock(pthread_mutex_t& mutex)
    {
        pthread_mutex_unlock(&mutex);
    }
public:
    Ringqueue(int cap = defaultnum)
    : ringqueue_(cap), _cap(cap), p_step(0),c_step(0)
    {
        sem_init(&pspace_sem, 0, cap);
        sem_init(&cdata_sem, 0, 0);

        pthread_mutex_init(&p_mutex, nullptr);
        pthread_mutex_init(&c_mutex, nullptr);
    }

    void Push(const T& in)
    {
        P(pspace_sem);
        Lock(p_mutex);

        ringqueue_[p_step] = in;
        p_step = (p_step+1)%_cap;

        UnLock(p_mutex);
        V(cdata_sem);
    }

    void Pop(T* out)
    {
        P(cdata_sem);
        Lock(c_mutex);

        *out = ringqueue_[c_step];
        c_step = (c_step+1)%_cap;

        UnLock(c_mutex);
        V(pspace_sem);
    }

    ~Ringqueue()
    {
        sem_destroy(&pspace_sem);
        sem_destroy(&cdata_sem);

        pthread_mutex_destroy(&p_mutex);
        pthread_mutex_destroy(&c_mutex);
    }
private:
    std::vector<T> ringqueue_;
    int _cap;

    int p_step;
    int c_step;

    sem_t pspace_sem;
    sem_t cdata_sem;

    pthread_mutex_t p_mutex;
    pthread_mutex_t c_mutex;
};